<?php
/**
 *    This file is part of OXID eShop Community Edition.
 *
 *    OXID eShop Community Edition is free software: you can redistribute it and/or modify
 *    it under the terms of the GNU General Public License as published by
 *    the Free Software Foundation, either version 3 of the License, or
 *    (at your option) any later version.
 *
 *    OXID eShop Community Edition is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU General Public License for more details.
 *
 *    You should have received a copy of the GNU General Public License
 *    along with OXID eShop Community Edition.  If not, see <http://www.gnu.org/licenses/>.
 *
 * @link      http://www.oxid-esales.com
 * @package   admin
 * @copyright (C) OXID eSales AG 2003-2010
 * @version OXID eShop CE
 * @version   SVN: $Id: article_stock.php 25466 2010-02-01 14:12:07Z alfonsas $
 */

/**
 * Admin article inventory manager.
 * Collects such information about article as stock quantity, delivery status,
 * stock message, etc; Updates information (on user submit).
 * Admin Menu: Manage Products -> Articles -> Inventory.
 * @package admin
 */
class Article_Inventory extends oxAdminDetails
{
    /**
     * Loads article Inventory information, passes it to Smarty engine and
     * returns name of template file "article_stock.tpl".
     *
     * @return string
     */
    public function render()
    {
        $myConfig = $this->getConfig();

        parent::render();
        $oSmarty = oxUtilsView::getInstance()->getSmarty();
        $oSmarty->assign( "oViewConf", $this->_aViewData["oViewConf"]);
        $oSmarty->assign( "shop", $this->_aViewData["shop"]);

        /* $this->sql_article = 'SELECT a.oxtitle, 
	s.invstock, (SELECT COUNT(*) FROM invitems i WHERE s.invoxid=i.invartid) AS invamount, 
	s.invsite, s.invstore, s.invrack, s.invlevel 
FROM oxarticles a, invarticles s 
WHERE 
	s.invoxid = \'1964\'
	AND a.oxid = s.invoxid';
        
        $this->sql_variants = 'SELECT (SELECT b.oxtitle FROM oxarticles b where b.oxid = \'531b537118f5f4d7a427cdb825440922\') AS oxtitle, a.oxvarselect, 
	s.invstock, (SELECT COUNT(*) FROM invitems i WHERE s.invoxid=i.invartid) AS invamount, 
	s.invsite, s.invstore, s.invrack, s.invlevel 
FROM oxarticles a, invarticles s 
WHERE 
	a.oxparentid = \'531b537118f5f4d7a427cdb825440922\'
	AND a.oxid = s.invoxid'; */
        
        $this->_aViewData["edit"] = $oArticle = oxNew( "oxarticle");

        $soxId = oxConfig::getParameter( "oxid");
        if ( $soxId != "-1" && isset( $soxId)) {

            // load object
            $oArticle->loadInLang( $this->_iEditLang, $soxId );

            // load object in other languages
            $oOtherLang = $oArticle->getAvailableInLangs();
            if (!isset($oOtherLang[$this->_iEditLang])) {
                // echo "language entry doesn't exist! using: ".key($oOtherLang);
                $oArticle->loadInLang( key($oOtherLang), $soxId );
            }

            foreach ( $oOtherLang as $id => $language) {
                $oLang= new oxStdClass();
                $oLang->sLangDesc = $language;
                $oLang->selected = ($id == $this->_iEditLang);
                $this->_aViewData["otherlang"][$id] =  clone $oLang;
            }


            // variant handling
            if ( $oArticle->oxarticles__oxparentid->value) {
                $oParentArticle = oxNew( "oxarticle");
                $oParentArticle->load( $oArticle->oxarticles__oxparentid->value);
                $this->_aViewData["parentarticle"] =  $oParentArticle;
                $this->_aViewData["oxparentid"] =  $oArticle->oxarticles__oxparentid->value;
            }

            $sShopID = $myConfig->getShopID();
            if ( $oArticle->oxarticles__oxvarcount->value == 0 ) {
                $sSql = "SELECT a.oxtitle, '-' AS oxvarselect, "
                        . "a.oxid, s.invoxid, oxartnum, a.oxstockflag, (a.oxbprice * s.invstock) as invbuysum, "
                        . "s.invstock, s.invsite, s.invstore, s.invrack, s.invlevel "
                        . "FROM oxarticles a, invarticles s "
                        . "WHERE "
                            . "s.invoxid = '$soxId' "
                            . "AND a.oxshopid = '$sShopID' "
                            . "AND a.oxid = s.invoxid ";
                
            } else {
                /*$sSql = "SELECT "
                        . "(SELECT b.oxtitle FROM oxarticles b where b.oxid = '$soxId') AS oxtitle, "
                        . "a.oxvarselect, s.invstock, (SELECT COUNT(*) FROM invitems i WHERE s.invoxid = i.invartid) AS invamount, "
                        . "s.invsite, s.invstore, s.invrack, s.invlevel "
                        . "FROM oxarticles a, invarticles s "
                        . "WHERE "
                            . "a.oxparentid = '$soxId' "
                            . "AND a.oxshopid = '$sShopID' "
                            . "AND a.oxid = s.invoxid ";*/
                $sSql = "SELECT "
                        . "(SELECT b.oxtitle FROM oxarticles b where b.oxid = '$soxId') AS oxtitle, "
                        . "(IF(oxbprice=0,(SELECT b.oxbprice FROM oxarticles b where b.oxid = '$soxId'),oxbprice) * invstock) AS invbuysum, "
                        . "oxid, invoxid, oxartnum, oxvarselect, oxstockflag, invsite, invstore, invrack, invlevel, invstock "
                        . "FROM oxarticles "
                        . "LEFT JOIN invarticles ON oxarticles.oxid=invarticles.invoxid "
                        . "WHERE oxparentid = '$soxId' " 
                            . "AND oxshopid = '$sShopID' "
                            . "AND oxactive = 1 "
                        . "ORDER BY oxsort";
            }
            
            
            /*$oPriceList = oxNew("oxlist");
            $oPriceList->init( 'oxbase', "oxprice2article" );
            $sQ = "select * from oxprice2article where oxartid = '$soxId' and oxshopid = '$sShopID' and (oxamount > 0 or oxamountto > 0) order by oxamount ";
            $oPriceList->selectstring( $sQ );

            $this->_aViewData["amountprices"] = $oPriceList;*/

            /*echo '<pre>SQL:<br>';
            echo $sSql;
            echo '</pre>';*/
            
            $aInventory = array();
            $rs = oxDb::getDb(true)->Execute($sSql);
			while (!$rs->EOF) {
                array_push($aInventory, $rs->fields);
                $rs->MoveNext();
            } 

            /*echo '<hr><pre>aInventory:<br>';
            echo print_r($aInventory);
            echo '</pre>';*/
            
            if (count($aInventory) == 0) {
                $sSql = "SELECT oxtitle, 0 AS invbuysum, oxid, '' AS invoxid, oxartnum, '-' AS oxvarselect, oxstockflag, "
                    . "'' as invsite, '' AS invstore, '' as invrack, '' AS invlevel, 0 AS invstock "
                    . "FROM oxarticles "
                    . "WHERE oxid = '$soxId' "
                        . "AND oxshopid = '$sShopID' ";
                $rs = oxDb::getDb(true)->Execute($sSql);
                array_push($aInventory, $rs->fields);
            }
            $oSmarty->assign("aInventory",$aInventory);
         
        }

        return "article_inventory.tpl";
    }

    /**
     * Save all inventory data
     * 
     * @param type $sOXID
     * @param type $aParams 
     */
    public function saveinventory($sOXID = null, $aParams = null)
    {
        if ( !isset( $sOXID ) && !isset( $aParams ) ) {
            $sOXID   = oxConfig::getParameter( "voxid" );
            $aParams = oxConfig::getParameter( "editval" );
        }
        
        // varianthandling
        $soxparentId = oxConfig::getParameter( "oxid" );
        if ( isset( $soxparentId) && $soxparentId && $soxparentId != "-1" ) {
            $aParams['oxarticles__oxparentid'] = $soxparentId;
        } else {
            unset( $aParams['oxarticles__oxparentid'] );
        }
        
        $oDb = oxDb::getDb();
        
        $iRows = oxConfig::getParameter( "rownum" );
        for ($i = 1; $i <= $iRows; $i++) {
            //$sNewId = $sNewId ? $sNewId : oxUtilsObject::getInstance()->generateUID();
            /*echo $iRows.'<br>';
            echo oxConfig::getParameter( "invstock_$i" )
                    .' / '.oxConfig::getParameter( "invoxid_$i" )
                    .' / '.oxUtilsObject::getInstance()->generateUID()
                    .' / '.oxConfig::getParameter( "invsite_$i" )
                    .' / '.oxConfig::getParameter( "invstore_$i" )
                    .' / '.oxConfig::getParameter( "invrack_$i" )
                    .' / '.oxConfig::getParameter( "invlevel_$i" )
                    .'<br>';*/
            $sInvID = oxConfig::getParameter( "invoxid_$i" );
            if (!empty($sInvID)) {
                // update the existing record
                $sSql = "UPDATE invarticles "
                        . "SET "
                            . "invsite = ".$oDb->quote(oxConfig::getParameter( "invsite_$i" )).", "
                            . "invstore = ".$oDb->quote(oxConfig::getParameter( "invstore_$i" )).", "
                            . "invrack = ".$oDb->quote(oxConfig::getParameter( "invrack_$i" )).", "
                            . "invlevel = ".$oDb->quote(oxConfig::getParameter( "invlevel_$i" )).", "
                            . "invstock = ".$oDb->quote(oxConfig::getParameter( "invstock_$i" ))." "
                        . "WHERE "
                            . "invoxid = ".$oDb->quote(oxConfig::getParameter( "oxid_$i" ))." ";
            } else {
                // insert a new record
                //$sNewInvID = oxUtilsObject::getInstance()->generateUID();
                $sSql = "INSERT INTO invarticles "
                        . "(invoxid, invsite, invstore, invrack, invlevel, invstock) "
                        . "VALUES ("
                            . $oDb->quote(oxConfig::getParameter( "oxid_$i" )) . ", "
                            . $oDb->quote(oxConfig::getParameter( "invsite_$i" )) . ", "
                            . $oDb->quote(oxConfig::getParameter( "invstore_$i" )) . ", "
                            . $oDb->quote(oxConfig::getParameter( "invrack_$i" )) . ", "
                            . $oDb->quote(oxConfig::getParameter( "invlevel_$i" )) . ", "
                            . $oDb->quote(oxConfig::getParameter( "invstock_$i" )) 
                            . ") ";
            }
            //echo '<pre>'.$sSql.'</pre>';
            $oDb->execute($sSql);
        }

    }
    
    /*public function sendorder() {
        $result = parent::sendorder();
        echo '*** It works ***';
        return $result;
    }*/
    

}